// CaptchaServlet.java
package com.ethereal.petmanagement.controller;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/captcha")
public class CaptchaController extends HttpServlet {
    private static final char[] chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789".toCharArray(); //验证码字符集
    private static final int LENGTH = 4; //验证码长度

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置不缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        //创建图片
        int width = 80, height = 30;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //获取图形上下文
        Graphics g = image.getGraphics();

        //生成随机背景
        Random random = new Random();
        g.setColor(getRandColor(200, 250));
        g.fillRect(0, 0, width, height);

        //设置字体
        g.setFont(new Font("Times New Roman", Font.PLAIN, 18));

        //随机生成干扰线
        g.setColor(getRandColor(160, 200));
        for (int i = 0; i < 20; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(x, y, x + xl, y + yl);
        }

        //生成随机验证码
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < LENGTH; i++) {
            String rand = String.valueOf(chars[random.nextInt(chars.length)]);
            sb.append(rand);
            //将验证码显示到图像中
            g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110),
                    20 + random.nextInt(110)));
            g.drawString(rand, 13 * i + 6, 16);
        }

        //释放图形上下文
        g.dispose();

        //将验证码存入session设置1分钟有效期
        HttpSession session = request.getSession();
        session.setAttribute("captcha", sb.toString());
        session.setMaxInactiveInterval(60);

        //输出图像到页面
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }

    //生成随机颜色
    private Color getRandColor(int fc, int bc) {
        Random random = new Random();
        if (fc > 255) fc = 255;
        if (bc > 255) bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
}